package com.netx.test.backups;
import com.netx.generics.tasks.BackgroundTask;
import com.netx.generics.tasks.ForegroundTask;
import com.netx.generics.tasks.TaskManager;
import com.netx.generics.tasks.TaskWorker;


public class TaskTester {

	public static void main(String[] args) throws Throwable {
		TaskTester tester = new TaskTester();
		//tester.testTasks();
		tester.testStopManager();
	}

	public void testTasks() {
		TaskManager manager = new TaskManager(1);
		manager.startTask(new BTask());
		manager.startTask(new FTask());
	}
	
	public void testStopManager() throws Exception {
		TaskManager manager = new TaskManager(10);
		manager.startTask(new BTask());
		Thread.sleep(1000);
		manager.startTask(new FTask());
		manager.stop();
	}
	
	private class BTask extends BackgroundTask {
		public BTask() {
			super();
			addWorker(new TWorker(10));
			addWorker(new TWorker(1));
		}
	}
	
	private class TWorker extends TaskWorker {
		private int _counter;
		private final int _numIterations;
		public TWorker(int numIterations) {
			_counter = 0;
			_numIterations = numIterations;
		}
		public void performWork() {
			System.out.println("background thread #"+(_counter+1));
			_counter++;
			if(_counter == _numIterations) {
				System.out.println("background thread: finished");
				markFinished();
			}
			else {
				try {
					Thread.sleep(500);
				}
				catch(InterruptedException ie) {
					System.out.println("interrupted, cleanup here...");
				}
			}
		}
	}

	private class FTask extends ForegroundTask {
		protected void performWork() {
			try {
				for(int i=1; i<=10; i++) {
					System.out.println("foreground thread #"+i);
					Thread.sleep(1);
				}
				System.out.println("foreground thread: finished");
			}
			catch(InterruptedException ie) {
				System.out.println("stopped, cleanup here...");
			}
		}
	}
}
